<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Http\Controllers\Controller;
use App\Models\AgentConfig;
use App\Models\AgentUser;
use App\Models\Registry;
use App\Services\AgentService;
use App\Services\RegistryService;
use Illuminate\Support\Arr;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class RegistryController extends Controller
{
    /** @var RegistryService */
    private $registryService;

    /** @var AgentService */
    private $agentService;

    /**
     * RegistryController constructor.
     */
    public function __construct(RegistryService $registryService, AgentService $agentService)
    {
        $this->registryService = $registryService;
        $this->agentService = $agentService;
    }

    /** 列表查询 */
    public function index()
    {
        $query = $this->myRegistryQuery()
            ->with(['user.auth'])
            ->when(request()->user_id, function ($q) {
                return $q->where('user_id', request()->user_id);
            })
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';

                return $q->where('product_name', 'like', $likeVal)->orWhere('register_id', 'like', $likeVal);
            })
            ->when(request()->mobile, function ($q) {
                return $q->whereHas('user', function ($q2) {
                    $likeVal = '%' . request()->mobile . '%';

                    return $q2->where('mobile', 'like', $likeVal);
                });
            })
            ->when(request()->start_date, function ($q) {
                return $q->whereDate('created_at', '>=', request()->start_date);
            })
            ->when(request()->end_date, function ($q) {
                return $q->whereDate('created_at', '>=', request()->end_date);
            })
            ->when(request()->status, function ($q) {
                return $q->where('status', request()->status);
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 查看登记详情 */
    public function show($id)
    {
        $registry = $this->myRegistryQuery()->find($id);
        if (!$registry) {
            throw new AdminException('无效的登记信息');
        }
        $registry->load([
            'productFiles', 'productImages', 'authors', 'owners',
            'attachFiles', 'auditHistories', 'user', 'order',
        ]);

        return $registry->toArray();
    }

    /** 查询代理版权登记价格设置 */
    public function getPriceSettings()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $categories = $this->registryService->proCat();
        $defaultPrice = $this->agentService->getAgentSetting($user->agent_id, AgentConfig::REGISTRY_DEFAULT_PRICE);
        $prices = json_decode($this->agentService->getAgentSetting($user->agent_id, AgentConfig::REGISTRY_PRICE_PER_CATEGORY), true);
        $perCategory = [];
        foreach ($categories as $category) {
            $name = Arr::get($category, 'name');
            $price = Arr::get($prices, $name, '');
            $perCategory[] = [
                'name' => $name,
                'price' => $price,
            ];
        }

        return [
            'default_price' => $defaultPrice,
            'per_category' => $perCategory,
        ];
    }

    /** 保存代理版权登记价格 */
    public function savePriceSettings()
    {
        request()->validate([
            'default_price' => 'required',
        ]);

        /** @var AgentUser $user */
        $user = auth()->user();
        $perCategoryPrices = request()->get('prices', []);
        $this->agentService->saveAgentSettings($user->agent_id, [
            AgentConfig::REGISTRY_DEFAULT_PRICE => request()->default_price,
            AgentConfig::REGISTRY_PRICE_PER_CATEGORY => json_encode($perCategoryPrices),
        ]);
    }

    private function myRegistryQuery()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        return Registry::query()->where('agent_id', $user->agent_id);
    }
}
